<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\lists\room;


use app\adminapi\lists\BaseAdminDataLists;
use app\common\lists\ListsExcelInterface;
use app\common\model\Config;
use app\common\model\Device;
use app\common\model\room\RoomApartment;
use app\common\model\room\RoomApartmentDevice;
use app\common\model\room\RoomApartmentLog;
use app\common\model\room\RoomApartmentUser;
use app\common\lists\ListsSearchInterface;
use app\common\model\room\RoomApartmentUserRecords;
use app\common\model\user\User;
use think\Db;


/**
 * 公寓用户关联列表
 * Class RoomApartmentUserLists
 * @package app\adminapi\listsroom
 */
class RoomApartmentUserLists extends BaseAdminDataLists implements ListsSearchInterface, ListsExcelInterface {

    protected $export_name = '进修公寓-导出';
    protected $export_lists = [];
    protected $export_fields = [];

    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function setSearch(): array {
        return [
            '=' => ['cid', 'rid', 'status', 'user_id'],
//            'between_time' => ['add_time'],

        ];
    }

    public function queryWhere() {
        $param = $this->request->param();
        $this_month = date("Ym");
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");
        $db = new Db();

        $where = $where_log = [];

        if (!empty($this->adminCid) && $this->adminCid !== 0) {
            $param['cb_ids'][0] = $this->adminCid;
        }

        if (!empty($param['cb_ids'])) {
            $where_a = [];

            if (!empty($param['cb_ids'][0])) {
                $where_a[] = ['cid', '=', $param['cb_ids'][0]];
            }
            if (!empty($param['cb_ids'][1])) {
                $where_a[] = ['bid', '=', $param['cb_ids'][1]];
            }
            $room_ids = RoomApartment::where([
                $where_a
            ])->column("id");

            $where[] = ["room_apartment_id", "in", $room_ids];
            $exp = "";
            foreach ($room_ids as $room_index => $room_id) {
                if ($room_index >= 1) {
                    $exp .= " or ";
                }
                $exp .= "FIND_IN_SET($room_id, room_ids)";
            }
            if (count($room_ids) > 0) {
                $where_log[] = ['', 'exp', $db->raw($exp)];
            } else {
                $where_log[] = ['room_ids', 'in', [0]];
            }
        }

        if (isset($param['user_keyword']) && $param['user_keyword'] != '') {
            $user_ids = User::alias("u")->where([
                ['real_name|mobile', 'like', '%' . $param['user_keyword'] . '%']
            ])->column("id");

            $where[] = ['user_id', 'in', $user_ids];
            $where_log[] = ['user_id', 'in', $user_ids];
        }

        if (isset($param['room_keyword']) && $param['room_keyword'] != '') {
            $room_ids = RoomApartment::where([
                ['name|address', 'like', '%' . $param['room_keyword'] . '%']
            ])->column("id");

            $where[] = ['room_apartment_id', 'in', $room_ids];

            $exp = "";
            foreach ($room_ids as $room_index => $room_id) {
                if ($room_index >= 1) {
                    $exp .= " or ";
                }
                $exp .= "FIND_IN_SET($room_id, room_ids)";
            }
            if (count($room_ids) > 0) {
                $where_log[] = ['', 'exp', $db->raw($exp)];
            } else {
                $where_log[] = ['room_ids', 'in', [0]];
            }
        }

        if ($this_month == $search_month) {
            return $where;
        } else {
            return $where_log;
        }
    }

    public function get_query() {
        $this_month = date("Ym");
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");
        $date_month = date("Y年m月");

        if ($this_month == $search_month) {
            return RoomApartmentUserRecords::field([
                "'0' as is_log",
                'room_apartment_id', "'" . $date_month . "' as date_time", // with查询数据
                'user_id', 'user_name', 'user_mobile', "GROUP_CONCAT(room_apartment_id) as room_ids",
            ])->where($this->queryWhere())->with([
                "allRoomStat",
            ])->group('user_id');
        } else {
            return RoomApartmentUser::field([
                "*",
                "'1' as is_log",
                "'" . $date_month . "' as date_time",
            ])->where($this->queryWhere())->where([
                ["log_date", "=", $search_month],
            ])->with([
                // "allRoomStat",
            ]);
        }
    }


    /**
     * @notes 获取公寓用户关联列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function lists(): array {
        $this_month = date("Ym");
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");
        $export = $this->request->param("export");

        $query = $this->get_query();

        if (!in_array($export, [1, 2])) {
            $query = $query->limit($this->limitOffset, $this->limitLength);
        }

        $user_arr = $query->select()->toArray();

        return (new RoomApartmentUserRecords())->data_append($user_arr);
    }

    /**
     * @notes 获取公寓用户关联数量
     * @return int
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function count(): int {
        return $this->get_query()->count();
    }

    public function print_stat_lists() {
        return $this->lists();
    }

    /**
     * 打印查询
     */
    public function print_lists() {
        $this_month = date("Ym");
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");
        $year = mb_substr($search_month, 0, 4);
        $month = mb_substr($search_month, 4, 2);
        $log_time_text = $year . "年" . $month . "月";

        $config_data = Config::get_room_all();
        $return_lists = [];

        if ($this_month == $search_month) {
            $lists = RoomApartmentUserRecords::field([
                'room_apartment_id', "'0' as is_log", // with查询数据
                'user_id', 'user_name', 'user_mobile', "GROUP_CONCAT(room_apartment_id) as room_ids",
            ])->where($this->queryWhere())->with([
                "allDeviceStat", // "allRoomStat",
            ])->group('user_id')->select()->toArray();
        } else {
            $lists = RoomApartmentUser::field([
                "*", "'1' as is_log",
            ])->where($this->queryWhere())->select()->toArray();
        }

        foreach ($lists as $k => $v) {
            if ($v['is_log'] == 1) {
                $room_ids = explode(",", $v['room_ids']);
                $v['allDeviceStat'] = RoomApartmentLog::where([
                    ["rid", "in", $room_ids],
                    ["log_time", "=", $v['log_time']],
                    ["log_date", "=", $v['log_date']],
                ])->with([
                    "s_device_stat", "d_device_stat",
                ])->append([
                    "room",
                ])->select()->toArray();
            }

            foreach ($v['allDeviceStat'] as $kk => $vv) {
                if ($v['is_log'] == 1) {
                    $vv['user_name'] = $v['user_name'];
                    $vv['user_mobile'] = $v['user_mobile'];
                }

                $vv['s_device_stat'][] = [
                    "base_number" => 0,
                    "reading" => $vv['room']['water_consumption'],
                    "use_total" => $vv['room']['water_consumption'],
                    "price" => $vv['room']['water_price'],
                    "total_fee" => $vv['room']['water_fee'],
                ];
                if (count($vv['s_device_stat']) > count($vv['d_device_stat'])) {
                    $more_arr = $vv['s_device_stat'];
                } else {
                    $more_arr = $vv['d_device_stat'];
                }
                // 打印水电设备处理
                foreach ($more_arr as $more_key => $more_val) {
                    if ($more_key == 0) {
                        $lift_fee = $vv['room']['lift_fee'] ?? 0;
                        $second_pressure_fee = $vv['room']['second_pressure_fee'] ?? 0;
                    } else {
                        $lift_fee = 0;
                        $second_pressure_fee = 0;
                    }

                    $return_lists[] = [
                        "room_name" => $vv['room']['name'], // 房间名
                        "user_name" => $vv['user_name'], // 住户名
                        "user_mobile" => $vv['user_mobile'], // 住户手机号

                        "s_base_number" => 1 * ($vv['s_device_stat'][$more_key]['base_number'] ?? 0), // 水表底数
                        "s_reading" => 1 * ($vv['s_device_stat'][$more_key]['reading'] ?? 0), // 水表读数
                        "s_use_total" => 1 * ($vv['s_device_stat'][$more_key]['use_total'] ?? 0) / $vv['room']['user_count'], // 用水量
                        "s_price" => 1 * ($vv['s_device_stat'][$more_key]["price"] ?? $config_data['room_apartment_s_device_price']['value']), // 水单价
                        "s_total_fee" => 1 * ($vv['s_device_stat'][$more_key]['total_fee'] ?? 0) / $vv['room']['user_count'], // 水表费用

                        "d_base_number" => 1 * ($vv['d_device_stat'][$more_key]['base_number'] ?? 0), // 电表底数
                        "d_reading" => 1 * ($vv['d_device_stat'][$more_key]['reading'] ?? 0), // 电表读数
                        "d_use_total" => 1 * ($vv['d_device_stat'][$more_key]['use_total'] ?? 0) / $vv['room']['user_count'], // 用电量
                        "d_price" => 1 * ($vv['d_device_stat'][$more_key]["price"] ?? $config_data['room_apartment_d_device_price']['value']), // 电单价
                        "d_total_fee" => 1 * ($vv['d_device_stat'][$more_key]['total_fee'] ?? 0) / $vv['room']['user_count'], // 电表费用

                        "lift_fee" => 1 * $lift_fee / $vv['room']['user_count'], // 电梯费
                        "second_pressure_fee" => 1 * $second_pressure_fee / $vv['room']['user_count'], // 加压费
                        "month_time" => $log_time_text, // 月份
                    ];
                }
            }
        }

        return $return_lists;
    }

    public function setExport($name, $lists, $fields) {
        $this->export_name = $name;
        $this->export_lists = $lists;
        $this->export_fields = $fields;
    }

    /**
     * @notes 导出文件名
     * @return string
     * @author 段誉
     * @date 2022/11/24 16:17
     */
    public function setFileName(): string {
        return $this->export_name;
    }

    /**
     * @notes 导出文件名
     * @return array
     * @author 段誉
     * @date 2022/11/24 16:17
     */
    public function setExcelLists() {
        return $this->export_lists;
    }

    /**
     * @notes 导出字段
     * @return string[]
     * @author 段誉
     * @date 2022/11/24 16:17
     */
    public function setExcelFields(): array {
        return $this->export_fields;
    }

}

